﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Windows;
using System.Windows.Controls;

using P2PChat.Net;
using P2PChat.Data;
using P2PChat.Data.Packets;
using P2PChat.Client.Data;

using System.Runtime.Serialization.Formatters.Binary;

namespace P2PChat.Client.Threading
{
    public static class Thread_ChatHandler
    {
        private static Listener chatListener = new Listener("0.0.0.0", GlobalConfig.ListeningPort);
        public static P2PChat.Log.ILog log = null;

        static Thread_ChatHandler()
        {
            chatListener.ClientConnect += new EventHandler<ListenerEventArgs>(chatListener_ClientConnect);
            chatListener.Listen();
        }

        public static void Exit() {
            chatListener.Stop();
        }

        private static void chatListener_ClientConnect(object sender, ListenerEventArgs e)
        {
            BinaryFormatter bf = new BinaryFormatter();
            try
            {
                NetPacket recvPacket = bf.Deserialize(e.Client.GetStream()) as NetPacket;
                if (recvPacket.Tag == PacketTag.Message)
                {
                    // 判断消息类型
                    if (recvPacket.Content is TextMessagePacket)
                    {
                        AcceptTextMessage(recvPacket.Content as TextMessagePacket, e.IP);
                    }
                }
                else throw new Exception("接收消息线程:服务器发送了错误的包或是遇到错误!");
            }
            catch (Exception ex)
            {
                if (log != null)
                {
                    log.Add(ex.Message);
                }
            }
        }

        private static void AcceptTextMessage(TextMessagePacket packet, System.Net.IPAddress ip)
        {
            int localSession = packet.ReceiverSession;
            // ### 判断是否为新的Session ###
            if (localSession == -1)
            {
                localSession = ChatSession.NewSession();
            }

            // ### 将数据存入Session中 ###
            // /MemberList/*
            if (ChatSession.Sessions[localSession].Element("MemberList") == null)
            {
                ChatSession.Sessions[localSession].Add(new XElement("MemberList"));
            }
            if (ChatSession.Sessions[localSession].Element("MemberList").Elements("Member").Count(x => 
                Guid.Parse(x.Attribute("GUID").Value) == packet.SenderId) == 0)
            {
                ChatSession.Sessions[localSession].Element("MemberList").Add(new XElement("Member",
                    new XAttribute("GUID", packet.SenderId.ToString()),
                    new XElement("SessionID", packet.SenderSession),
                    new XElement("IPEndPoint",
                        new XElement("IPAddress", ip.ToString()),
                        new XElement("Port", packet.ListeningPort))));
            }
            
            // /MessageList/*
            if (ChatSession.Sessions[localSession].Element("MessageList") == null)
            {
                ChatSession.Sessions[localSession].Add(new XElement("MessageList"));
            }
            ChatSession.Sessions[localSession].Element("MessageList").Add(
                new XElement("Text", new XAttribute("SenderID", packet.SenderId.ToString()),
                    new XAttribute("Index", ChatSession.Sessions[localSession].Element("MessageList").Elements().Count() + 1),
                    packet.Message));

            // ### 刷新窗口 ###
            TextBlock lb_NewTextMessage = new TextBlock()
            {
                Text = string.Format(@"{0}: {1}", 
                FriendList.List.Elements("Group").Elements("Friend").Where(x => 
                     Guid.Parse(x.Attribute("GUID").Value) == packet.SenderId).
                     First().Element("PersonalInfo").Element("Nickname").Value, 
                packet.Message),
                TextWrapping = TextWrapping.Wrap,
            };
            ChatSession.Windows[localSession].MessagePanelChildren.Add(lb_NewTextMessage);
        }
    }
}
